package gspring

import (
	"gitee.com/hongzhaomin/gspring/tools"
	"reflect"
	"sync"
)

var (
	beanLock               = new(sync.RWMutex)
	registeredGspringBeans = make([]any, 0)
)

// Register 将bean注册到gspring容器中，交给gspring管理
// 在整合其他框架的时候可以将需要交给gspring管理的bean，在init函数中调用此方法注册进来
func Register(beans ...any) {
	for _, bean := range beans {
		register(bean)
	}
}

func register(bean any) {
	beanLock.Lock()
	defer beanLock.Unlock()
	tools.Assert().NotNil(bean, "register bean must not be nil")

	rv := reflect.Indirect(reflect.ValueOf(bean))
	fullPathName := tools.GetFullPathNameByRt(rv.Type())
	tools.Assert().IsTrue(rv.Kind() == reflect.Struct, "bean must be struct kind: "+fullPathName)

	contains := tools.Contains(registeredGspringBeans, bean)
	tools.Assert().IsFalse(contains, "bean can not register twice: "+fullPathName)

	registeredGspringBeans = append(registeredGspringBeans, bean)
}
